boolean firstPress = false;
int x0 ;
int y0 ;
int x1 ;
int y1 ;

void setup() {
  size(640, 360);
  background(255);
  noFill();
}

void mousePressed() {
  if (firstPress) {
    x1 = mouseX;
    y1 = mouseY;
    firstPress = false;
    stroke(random(1, 250), random(1, 250), random(1, 250));
  }
  else {
    x0 = mouseX;
    y0 = mouseY;
    firstPress = true;
  }
}

void draw() {
  //if (firstPress && x1!= mouseX && y1 !=  mouseY) {
  if (firstPress) {
    background(255);
    x1 = mouseX;
    y1 = mouseY;

    if (x0 >= x1-1 && x0 <= x1+1) {
      int y = min(y0, y1);
      int x = x0;
      while (y<max (y0, y1)) {
        point(x, y);
        y += 1;
      }
    }
    else {
      int x,y;
      int endX,endY;
      boolean up;
      int dy;
      int dx;

      if (x0<x1) {
        x = x0;
        endX = x1;
        endY = y1;
        y = y0;
        dy = y1-y0;
        dx = x1-x0;
      }
      else {
        x = x1;
        endX = x0;
        endY = y0;
        y = y1;
        dy = y0-y1;
        dx = x0-x1;
      }
      up = endY < y;
      // f(x,y) = m*x + b - y = 0
      if (abs(dy/dx)<1) {
        int d = 2*dy + ((up)?dx:-1*dx);
        while ( x < endX) {
          point(x, y);
          x += 1;
          if(up){
            y += ((d<0)?-1:0);
            d += 2*dy + ((d<0)?2*dx:0);
          }else{
            y += ((d>0)?1:0);
            d += 2*dy + ((d>0)?-2*dx:0);
          }
        }
      }
      else {
        int d = dy + ((up)?2*dx:-2*dx);
        while (x < endX || y < endY ) {
          point(x, y);
          if(up){
            y += -1;
            x += (d>0)?1:0;
            d += 2*dx + ((d>0)?2*dy:0);
          }else{
            y += 1;
            x += (d<0)?1:0;
            d += -2*dx + ((d<0)?2*dy:0);
          }
        }
      }
    }
  }
}


